package com.webserver.core;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.controller.ArticleController;
import com.webserver.controller.ToolsController;
import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static File root;
    private static File staticDir;

    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        dispatchRequest(request, response);
        response.addHeader("Server","WebServer");
    }

    private void dispatchRequest(HttpServletRequest request, HttpServletResponse response){
        String path = request.getRequsetURI();
        System.out.println("------"+path+"------");
        //首先判断该请求是否为请求一个业务
        try {
           HandlerMapping.MethodMapping mm = HandlerMapping.getMethod(path);
           if(mm!=null){
               Object controller = mm.getController();
               Method method = mm.getMethod();
               method.invoke(controller,request,response);
               return;
           }
        }catch(Exception e){
            e.printStackTrace();
        }

        File file = new File(staticDir,path);
        System.out.println("资源是否存在:"+file.exists());
        if(file.isFile()){
            response.setContentFile(file);
        }else{
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            //response.setContentFile(new File(staticDir,"root/404.html"));
            file = new File(staticDir,"root/404.html");
            response.setContentFile(file);
        }
    }

}
